<template>
	<view class="attendance-manage-container"
		:class="{ 'landscape-mode': isLandscape, 'showFullScreenImage': showFullScreenImage }">
		<!-- 顶部标题 - 只在竖屏显示 -->
		<view class="header" v-if="!isLandscape">
			<view class=""></view>
			<view class="terminal-selector" @tap="toggleCompanySelector">
				<text class="terminal-title">{{ selectedCompany.name }}</text>
				<uv-icon name="arrow-down" color="#333" size="20"></uv-icon>
			</view>

			<image src="/static/uniapp/map.png" mode="" style="width: 40rpx;height: 40rpx;margin-right: 30rpx;"
				@tap="toggleFullScreenImage('/static/uniapp/work.png')"></image>
		</view>
		<!-- 周选择器 - 只在竖屏显示 -->
		<view class="week-selector" v-if="!isLandscape">
			<view class="week-label">
				<text>Week of</text>
				<text class="line"> |</text>
			</view>
			<view class="date-picker" @click="showDatePicker = true">
				<image class="calendar-icon" src="/static/uniapp/duration.png" mode="aspectFit"></image>
				<text class="selected-date">{{ getOrdinalDay(selectedDateObj.getDate()) }}</text>
				<image src="/static/uniapp/arrow-down.png" mode="" style="width: 40rpx;height: 40rpx;"></image>
			</view>
		</view>
		<!-- 图表 -->
		<view class="chart-container" v-if="!isLandscape">
			<view class="chart-header">
				<view class="legend-item">
					<view class="legend-dot factory-dot"></view>
					<text>Factory</text>
				</view>
				<view class="legend-item">
					<view class="legend-dot company-dot"></view>
					<text>Company</text>
				</view>
			</view>
			<view class="chart-title">
				<text>Service</text>
			</view>
			<view class="echarts-box">
				<view class="echarts-container" id="performanceChart"></view>
			</view>
		</view>



		<!-- 主内容区域 -->
		<view class="main-content">

			<!-- 员工表格 -->
			<view class="employee-table">
				<!-- 导出按钮 - 只在竖屏显示 -->
				<view class="export-action">

					<image class="export-icon" src="/static/uniapp/del.png" mode="aspectFit"
						@click="toggleFieldsVisibility"></image>
					<image class="export-icon" src="/static/uniapp/export.png" mode="aspectFit"
						@click="toggleOrientation"></image>
				</view>
				<!-- 表格区域 -->
				<view class="table-container">
					<!-- 水平滚动容器 -->
					<scroll-view :show-scrollbar="false" scroll-x class="scroll-view-x"
						:class="{ 'landscape-scroll': isLandscape }" @scroll="onTableScroll" :scroll-left="scrollLeft">
						<!-- 表头 -->
						<view class="table-header">
							<view class="header-cell edit-cell">

							</view>
							<view class="header-cell employee-name">
								<text>Employee Name</text>
							</view>
							<view class="header-cell fedex-id">
								<text>Fedex ID</text>
							</view>

							<view class="header-cell employee-id">
								<text>Employee ID</text>
							</view>
							<view class="header-cell fedex-id">
								<text>Work area ID</text>
							</view>
							<!-- 可以隐藏和显示的字段组合 -->
							<view class="header-cell field-cell" v-for="(field, fieldIndex) in customFields"
								:key="'field-' + fieldIndex" v-show="field.visible">
								<text>{{ field.name }}</text>
							</view>
							<view class="header-cell index-id">
								<text>Idex Name</text>
							</view>
							<view class="header-cell date-day-container" v-for="(date, index) in headerDates"
								:key="index">
								<text class="date-text">{{ date.dateText }}</text>
								<text class="day-text">{{ date.dayText }}</text>
							</view>
						</view>
					</scroll-view>

					<!-- 表格内容 -->
					<scroll-view scroll-y class="table-body" @scroll="onVerticalScroll" :scroll-top="scrollTop"
						@refresherpulling="onPulling" @refresherrefresh="onRefresh" @scrolltolower="onLoadMore"
						:refresher-enabled="true" :refresher-triggered="isRefreshing" :refresher-threshold="45"
						refresher-background="#f5f5f5">
						<scroll-view scroll-x class="scroll-view-x" :class="{ 'landscape-scroll': isLandscape }"
							@scroll="onContentScroll" :scroll-left="scrollLeft">
							<view v-for="(item, index) in employeeList" :key="index" class="table-row">
								<view class="cell edit-cell">
									<image class="edit-icon" src="/static/uniapp/edit.png" mode="aspectFit"
										@click="editEmployee"></image>
								</view>
								<view class="cell employee-name">
									<text>{{ item.Employeename }}</text>
								</view>
								<view class="cell fedex-id">
									<text>{{ item.FedexID }}</text>
								</view>
								<view class="cell employee-id">
									<text>{{ item.SystemID }}</text>
								</view>
								<view class="cell fedex-id">
									<text>{{ item.WorkareaID || 'N/A' }}</text>
								</view>
								<view class="cell  date-day-container">
									<text>Service</text>
									<text>Violation</text>
									<text>Ask for leave</text>
								</view>
								<view class="cell  date-day-container" v-for="(field, fieldIndex) in item.Indexname" :key="fieldIndex">
									<text>{{ field.Service }}</text>
									<text>{{ field.Violation }}</text>
									<text>{{ field.Askforleave }}</text>
								</view>
							</view>
							<!-- 加载更多区域 -->
							<!-- <view class="load-more-container">
								<view class="loading-more" v-if="isLoading">
									<view class="loading-spinner"></view>
									<text>Loading...</text>
								</view>
								<view class="load-more-btn" v-else-if="hasMore" @tap="onLoadMore">
									<text>Load More</text>
								</view>
								<view class="no-more" v-else>
									<text>No more data</text>
								</view>
							</view> -->
						</scroll-view>
					</scroll-view>
				</view>
			</view>
		</view>

		<!-- 底部导出按钮 - 固定在底部，只在竖屏显示 -->
		<view class="footer" v-if="!isLandscape">
			<view class="export-buttons">
				<uv-button class="btn reject-btn" color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))" shape="circle" type="primary" icon="download" text="Excel" @click="exportExcel"></uv-button>
				<!-- <view class="export-btn excel-btn btn submit" @click="exportExcel">
					<uv-icon size="30" color="#fff" name="download"></uv-icon>
					<text>Excel</text>
				</view> -->
				<uv-button class="btn reject-btn" color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))" shape="circle" type="primary" icon="download" text="PDF" @click="exportPDF"></uv-button>
				<!-- <view class="export-btn pdf-btn btn submit" @click="exportPDF">
					<uv-icon size="30" color="#fff" name="download"></uv-icon>
					<text>PDF</text>
				</view> -->
			</view>
		</view>

		<!-- 添加横屏切换按钮 -->
		<!-- <view class="orientation-toggle" @click="toggleOrientation">
			<text>{{isLandscape ? '切换竖屏' : '切换横屏'}}</text>
		</view> -->

		<!-- 日期选择弹窗 -->
		<view class="date-picker-popup" v-if="showDatePicker" @tap.stop>
			<view class="date-picker-content" @tap.stop>
				<!-- 日历头部 -->
				<view class="calendar-header">
					<view class="prev-month" @tap="changeMonth(-1)">
						<image class="nav-arrow" src="/static/uniapp/arrow-left.png">
						</image>
					</view>
					<view class="current-month">
						<text>{{ currentMonth }} {{ currentYear }}</text>
					</view>
					<view class="next-month" @tap="changeMonth(1)">
						<image class="nav-arrow" src="/static/uniapp/arrow-right.png"></image>
					</view>
				</view>

				<!-- 星期标题 -->
				<view class="week-days">
					<view class="week-day" v-for="(day, index) in weekDays" :key="index"
						:class="{ 'friday': index === 5 }">
						<text>{{ day }}</text>
					</view>
				</view>

				<!-- 日期网格 -->
				<view class="calendar-grid">
					<view v-for="(date, index) in calendarDays" :key="index" class="calendar-day" :class="{
						'other-month': date.otherMonth,
						'selected': isDateSelected(date),
						'in-range': isInDateRange(date),
						'friday': date.date.getDay() === 5 && !date.otherMonth,
						'selectable': date.date.getDay() === 5 && !date.otherMonth,
						'non-selectable': date.date.getDay() !== 5 || date.otherMonth
					}" @tap="(date.date.getDay() === 5 && !date.otherMonth) ? selectCalendarDate(date) : null">
						<text>{{ date.day }}</text>
					</view>
				</view>

				<!-- 按钮区域 -->
				<view class="calendar-actions">
					<view class="submit-btn" @tap="submitDateSelection">
						<text>Submit Date</text>
					</view>
					<view class="close-btn" @tap="showDatePicker = false">
						<text>Close</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 公司选择弹窗 -->
		<view class="company-selector-popup" v-if="showCompanySelector" @tap="showCompanySelector = false">
			<view class="company-selector-content" @tap.stop>
				<view class="company-selector-title">
					<text>选择公司</text>
				</view>

				<view class="company-list">
					<view class="company-item" @tap="selectCompany('公司一')"
						:class="{ active: selectedCompany === 'Terminal One' }">
						<view class="radio-circle" :class="{ 'radio-selected': selectedCompany === 'Terminal One' }">
						</view>
						<text>公司一</text>
					</view>

					<view class="company-item" @tap="selectCompany('公司二')"
						:class="{ active: selectedCompany === 'Terminal Two' }">
						<view class="radio-circle" :class="{ 'radio-selected': selectedCompany === 'Terminal Two' }">
						</view>
						<text>公司二</text>
					</view>
				</view>

				<view class="close-company-btn" @tap="showCompanySelector = false">
					<text>Close</text>
				</view>
			</view>
		</view>

		<!-- Update the full-screen image viewer to fill the screen -->
		<view class="fullscreen-image-overlay" v-if="showFullScreenImage" @tap.stop="closeFullScreenImage">
			<view class="zoom-container" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" @tap.stop>
				<image class="fullscreen-image" :src="fullScreenImageSrc" mode="aspectFill"
					:style="{ transform: `scale(${imageScale})`, transition: isScaling ? 'none' : 'transform 0.3s' }">
				</image>
			</view>
			<view class="close-fullscreen-btn" @tap.stop="closeFullScreenImage">
				<text>×</text>
			</view>
		</view>
	</view>
</template>

<script>
// 引入 echarts
import * as echarts from 'echarts';
import { PerformanceTable, getEchartsData, workAreaMap } from '@/api/home'
import { getaddressBook, getMyCompanyList } from '@/api/approval'
import { DownloadFile } from '@/util/index.js'

export default {
	data() {
		return {
			isLandscape: false,
			selectedCompany: 'Terminal Name',
			showCompanySelector: false,
			selectedDate: 'Dec 28th',
			showDatePicker: false,
			showFullScreenImage: false,
			fullScreenImageSrc: '/static/uniapp/work.png',
			imageScale: 1,
			initialDistance: 0,
			isScaling: false,
			currentMonth: 'November',
			currentYear: 2025,
			weekDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
			selectedDateObj: new Date(),
			rangeStart: null,
			rangeEnd: null,
			calendarDays: [],
			scrollLeft: 0,
			
			scrollTop: 0,
			dateList: [
				'Dec 7th',
				'Dec 14th',
				'Dec 21st',
				'Dec 28th',
				'Jan 4th',
				'Jan 11th',
				'Jan 18th'
			],
			// 图表数据
			chartInstance: null,
			chartData: {
				xAxis: ['12-21', '12-22', '12-23', '12-24', '12-25', '12-26', '12-27'],
				factory: [38, 55, 35, 75, 35, 45, 15],
				company: [28, 25, 65, 68, 45, 38, 42]
			},
			employeeList: [],
			// 添加自定义字段数据
			customFields: [
				{ name: 'VScan Pkgs', visible: false },
				{ name: 'Del Stps', visible: false },
				{ name: 'PU Stps', visible: false },
				{ name: 'DIFF', visible: false },
				{ name: 'Act Del Stps', visible: false },
				{ name: 'Act PU Pkgs', visible: false },
				{ name: 'ILS%', visible: false },
				{ name: 'ILS Impact Pkgs', visible: false },
				{ name: 'Non delvd Stps', visible: false },
				{ name: 'Code 85', visible: false },
				{ name: 'All Status Code Pkgs', visible: false },
				{ name: 'PL ML', visible: false },
				{ name: 'DNA', visible: false },
				{ name: 'Date Certain', visible: false },
				{ name: 'Snd Agn', visible: false },
				{ name: 'Excs', visible: false },
				{ name: 'VSA vs STAR', visible: false },
				{ name: 'Returns Scans', visible: false },
				{ name: 'Miles', visible: false },
				{ name: 'E/L PUs', visible: false }
			],
			areAllFieldsVisible: false,
			pageSize: 10,
			currentPage: 1,
			isRefreshing: false,
			hasMore: true,
			allEmployeeList: [], // 存储所有数据
			displayEmployeeList: [], // 当前显示的数据
			isLoading: false,
			isEditMode: false,
		}
	},
	computed: {
		// 计算表头显示的7天日期（从selectedDateObj往前推6天）
		headerDates() {
			if (!this.selectedDateObj) return [];

			const dates = [];
			// 从选中日期开始，往前推6天
			for (let i = 6; i >= 0; i--) {
				const date = new Date(this.selectedDateObj);
				date.setDate(date.getDate() - i);

				// 格式化日期为 YYYY.M.D
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				const day = date.getDate();

				// 获取星期几
				const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
				const weekday = weekdays[date.getDay()];

				dates.push({
					dateText: `${year}.${month}.${day}`,
					dayText: weekday
				});
			}

			return dates;
		}
	},
	onLoad() {
		this.getlist()
		this.getTablelist()
		workAreaMap().then(res => {
				this.fullScreenImageSrc = res.map
		})
	},
	methods: {
		// 初始化图表
		
	async initChart() {
			// 确保DOM已渲染
			this.chartData = await getEchartsData({date: this.selectedDateObj.getDate()})
			setTimeout(() => {
				const chartDom = document.getElementById('performanceChart');
				if (!chartDom) {
					console.error('Chart container not found');
					return;
				}

				this.chartInstance = echarts.init(chartDom);

				// 设置图表配置
				const option = {
					backgroundColor: 'transparent',
					grid: {
						left: '3%',
						right: '4%',
						bottom: '3%',
						top: '5%',
						containLabel: true
					},
					xAxis: {
						type: 'category',
						boundaryGap: false,
						data: this.chartData.xAxis,
						axisLine: {
							lineStyle: {
								color: '#E0E0E0'
							}
						},
						axisTick: {
							show: false
						}
					},
					yAxis: {
						type: 'value',
						min: 0,
						max: 100,
						interval: 25,
						axisLabel: {
							formatter: '{value}%'
						},
						splitLine: {
							lineStyle: {
								color: '#E0E0E0'
							}
						},
						axisLine: {
							show: false
						},
						axisTick: {
							show: false
						}
					},
					series: [
						{
							name: 'Factory',
							type: 'line',
							data: this.chartData.factory,
							smooth: false,
							symbol: 'none',
							lineStyle: {
								width: 1.5,
								color: '#00C7F2'
							}
						},
						{
							name: 'Company',
							type: 'line',
							data: this.chartData.company,
							smooth: false,
							symbol: 'none',
							lineStyle: {
								width: 1.5,
								color: '#0FCA7A'
							}
						}
					]
				};

				// 渲染图表
				this.chartInstance.setOption(option);
				// 监听窗口大小变化，重新绘制图表
				window.addEventListener('resize', this.resizeChart);
			}, 300);
		},
		async getlist() {
			this.companyList = await getMyCompanyList() || []
			this.selectedCompany = this.companyList[0]
			this.companyId = this.companyList[0].id
		},
		async getTablelist(is_report = 0) {
			let apiData = {
				date: this.$dayjs(this.selectedDateObj).format('YYYY-MM-DD'),
				company_id: this.selectedCompany.id,
				is_report,
				report_type: 1,
			}
			let list = await PerformanceTable(apiData) || []
			if (is_report) {
				DownloadFile(list.excel )
				return
			}
			this.employeeList = list
		},
		editEmployee() {
			uni.navigateTo({
				url: '/pages/Performance/performanceEdit'
			});
		},
		// 重新绘制图表
		resizeChart() {
			if (this.chartInstance) {
				this.chartInstance.resize();
			}
		},
		// 屏幕旋转方法
		toggleOrientation() {
			this.isLandscape = !this.isLandscape;
			// 使用更兼容的方式控制屏幕方向
			try {
				// 检查 plus 环境是否可用（App环境）
				if (typeof plus !== 'undefined') {
					if (this.isLandscape) {
						// 切换到横屏
						plus.screen.lockOrientation('landscape');
					} else {
						// 切换到竖屏
						plus.screen.lockOrientation('portrait');
					}
					return;
				}

				// H5环境尝试使用Web API
				if (typeof screen !== 'undefined' && screen.orientation) {
					if (this.isLandscape) {
						screen.orientation.lock('landscape').catch(err => {
							console.error('无法锁定横屏', err);
						});
					} else {
						screen.orientation.lock('portrait').catch(err => {
							console.error('无法锁定竖屏', err);
						});
					}
				}
			} catch (e) {
				console.error('设置屏幕方向失败', e);
				// 至少在UI上反映出状态变化
				this.isLandscape = !this.isLandscape;
			}
		},

		// 监听设备方向变化
		listenOrientationChange() {
			const self = this;

			// 使用uni-app监听
			uni.onWindowResize(() => {
				const info = uni.getWindowInfo();
				if (info.windowWidth > info.windowHeight) {
					self.isLandscape = true;
				} else {
					self.isLandscape = false;
				}
			});

			// 浏览器API备选
			if (typeof window !== 'undefined') {
				window.addEventListener('orientationchange', function () {
					if (window.orientation === 90 || window.orientation === -90) {
						self.isLandscape = true;
					} else {
						self.isLandscape = false;
					}
				});
			}
		},

		// 公司选择方法
		toggleCompanySelector() {
			console.log('Terminal selector clicked');
			this.showCompanySelector = !this.showCompanySelector;
		},
		selectCompany(company) {
			this.selectedCompany = company;
			this.showCompanySelector = false;
		},

		// 日历相关方法
		generateCalendar() {
			// 使用更新后的方法生成初始日历
			const monthIndex = this.getMonthIndex(this.currentMonth);
			this.updateCalendarForMonth(monthIndex);
		},

		getMonthIndex(monthName) {
			const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
				'October', 'November', 'December'
			];
			return months.indexOf(monthName);
		},

		changeMonth(delta) {
			// 处理月份切换
			const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
				'October', 'November', 'December'
			];
			const currentIndex = months.indexOf(this.currentMonth);
			let newIndex = currentIndex + delta;

			if (newIndex < 0) {
				newIndex = 11;
				this.currentYear--;
			} else if (newIndex > 11) {
				newIndex = 0;
				this.currentYear++;
			}

			this.currentMonth = months[newIndex];

			// 根据新月份更新日历数据
			this.updateCalendarForMonth(newIndex);
		},

		updateCalendarForMonth(monthIndex) {
			// 基于月份更新日历数据
			const year = this.currentYear;
			const month = monthIndex;

			// 计算当月第一天是星期几
			const firstDay = new Date(year, month, 1).getDay();
			// 计算当月有多少天
			const daysInMonth = new Date(year, month + 1, 0).getDate();
			// 计算上月有多少天
			const daysInPrevMonth = new Date(year, month, 0).getDate();

			let calendarDays = [];

			// 添加上个月的日期
			const prevMonth = month === 0 ? 11 : month - 1;
			const prevYear = month === 0 ? year - 1 : year;

			for (let i = 0; i < firstDay; i++) {
				const day = daysInPrevMonth - firstDay + i + 1;
				calendarDays.push({
					day: day,
					otherMonth: true,
					date: new Date(prevYear, prevMonth, day)
				});
			}

			// 添加当月的日期
			for (let i = 1; i <= daysInMonth; i++) {
				calendarDays.push({
					day: i,
					otherMonth: false,
					date: new Date(year, month, i)
				});
			}

			// 添加下个月的日期（补齐到42个格子，即6行7列）
			const nextMonth = month === 11 ? 0 : month + 1;
			const nextYear = month === 11 ? year + 1 : year;
			const remainingDays = 42 - calendarDays.length;

			for (let i = 1; i <= remainingDays; i++) {
				calendarDays.push({
					day: i,
					otherMonth: true,
					date: new Date(nextYear, nextMonth, i)
				});
			}

			this.calendarDays = calendarDays;

			// 更新月份相关的选中日期
			this.updateSelectedDatesForMonth(month);
		},

		updateSelectedDatesForMonth(month) {
			// Set default selected date for current month if none is selected
			if (!this.selectedDateObj) {
				// Find the first Friday of the month
				const firstDayOfMonth = new Date(this.currentYear, month, 1);
				const daysUntilFriday = (5 - firstDayOfMonth.getDay() + 7) % 7;
				const firstFriday = new Date(this.currentYear, month, 1 + daysUntilFriday);

				this.selectedDateObj = firstFriday;
			}
		},

		isDateSelected(date) {
			// Check if the provided date matches the selected date
			if (!this.selectedDateObj) return false;
			console.log('selectedDateObj',this.selectedDateObj.getMonth(), this.selectedDateObj.getDate(), date.date.getDate(), date.date.getMonth())
			return this.selectedDateObj.getFullYear() === date.date.getFullYear() &&
				this.selectedDateObj.getMonth() === date.date.getMonth() &&
				this.selectedDateObj.getDate() === date.date.getDate();
		},

		isInDateRange(date) {
			// For single date selection, this is the same as isDateSelected
			return this.isDateSelected(date);
		},

		selectCalendarDate(date) {
			// Only allow selecting Fridays
			if (date.date.getDay() === 5) { // 5 is Friday (0 is Sunday, 1 is Monday, etc.)
				this.selectedDateObj = date.date;
				this.showDatePicker = false
			} else {
				// Optional: Show a notification that only Fridays can be selected
				uni.showToast({
					title: 'Only Fridays can be selected',
					icon: 'none',
					duration: 2000
				});
			}
		},

		submitDateSelection() {
			// Update the selected date display based on single selected date
			if (this.selectedDateObj) {
				const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
				const month = months[this.selectedDateObj.getMonth()];
				const day = this.getOrdinalDay(this.selectedDateObj.getDate());

				this.selectedDate = `${month} ${day}`;
			}
			this.showDatePicker = false;
		},
		getOrdinalDay(day) {
			if (day > 3 && day < 21) return day + "th";
			switch (day % 10) {
				case 1:
					return day + " st";
				case 2:
					return day + " nd";
				case 3:
					return day + " rd";
				default:
					return day + " th";
			}
		},

		// 原有方法
		selectDate(date) {
			this.selectedDate = date;
			this.showDatePicker = false;
		},
		exportExcel() {
			// 导出Excel文件
			uni.showToast({
				title: 'Exporting Excel...',
				icon: 'none'
			});
		},
		exportPDF() {
			// 导出PDF文件
			uni.showToast({
				title: 'Exporting PDF...',
				icon: 'none'
			});
		},
		// 表格滚动同步方法
		onTableScroll(e) {
			// 更新滚动位置状态
			this.scrollLeft = e.detail.scrollLeft;
		},
		onContentScroll(e) {
			// 更新滚动位置状态
			this.scrollLeft = e.detail.scrollLeft;
		},
		onVerticalScroll(e) {
			this.scrollTop = e.detail.scrollTop;
		},
		// Full screen image handling
		toggleFullScreenImage(imageSrc) {
			if (imageSrc) {
				// this.fullScreenImageSrc = imageSrc;
				this.showFullScreenImage = true;
				this.imageScale = 1; // Reset scale when opening
			} else {
				this.closeFullScreenImage();
			}
		},

		closeFullScreenImage() {
			this.showFullScreenImage = false;
		},

		// Touch handlers for zoom
		touchStart(e) {
			if (e.touches.length === 2) {
				// Calculate initial distance between two fingers
				const touch1 = e.touches[0];
				const touch2 = e.touches[1];
				this.initialDistance = Math.sqrt(
					Math.pow(touch2.pageX - touch1.pageX, 2) +
					Math.pow(touch2.pageY - touch1.pageY, 2)
				);
				this.isScaling = true;
			}
		},

		touchMove(e) {
			if (e.touches.length === 2 && this.isScaling) {
				// Calculate new distance
				const touch1 = e.touches[0];
				const touch2 = e.touches[1];
				const currentDistance = Math.sqrt(
					Math.pow(touch2.pageX - touch1.pageX, 2) +
					Math.pow(touch2.pageY - touch1.pageY, 2)
				);

				// Calculate scale change
				if (this.initialDistance > 0) {
					const newScale = this.imageScale * (currentDistance / this.initialDistance);
					// Limit scale to reasonable values
					if (newScale >= 0.5 && newScale <= 5) {
						this.imageScale = newScale;
					}
				}

				// Update initial distance for next move
				this.initialDistance = currentDistance;
			}
		},

		touchEnd() {
			this.isScaling = false;
		},

		zoomIn() {
			if (this.imageScale < 5) {
				this.imageScale = Math.min(5, this.imageScale + 0.5);
			}
		},

		zoomOut() {
			if (this.imageScale > 0.5) {
				this.imageScale = Math.max(0.5, this.imageScale - 0.5);
			}
		},

		resetZoom() {
			this.imageScale = 1;
		},
		// Toggle field visibility
		toggleFieldsVisibility() {
			// Toggle the state
			this.areAllFieldsVisible = !this.areAllFieldsVisible;

			// Update all fields visibility based on the new state
			this.customFields.forEach(field => {
				field.visible = this.areAllFieldsVisible;
			});
		},
		// 生成模拟数据
		generateMockData() {
			const mockData = [];
			for (let i = 1; i <= 50; i++) {
				mockData.push({
					name: `Employee ${i}`,
					fedexId: `1338980${String(i).padStart(4, '0')}`,
					employeeId: `EMP${String(i).padStart(4, '0')}`,
					workAreaId: `WA-${String(i).padStart(3, '0')}`,
					field1: `数据${i}`,
					field2: `数据${i}`,
					field3: `数据${i}`,
					field4: `数据${i}`,
					field5: `数据${i}`,
					field6: `数据${i}`,
					field7: `数据${i}`,
					field8: `数据${i}`,
					field9: `数据${i}`,
					field10: `数据${i}`,
					am: '8:00',
					pm: '17:00'
				});
			}
			return mockData;
		},

		// 初始化数据
		initData() {
			this.allEmployeeList = this.generateMockData();
			this.loadPageData();
		},

		// 加载分页数据
		loadPageData() {
			if (this.isLoading) return;

			this.isLoading = true;
			const start = (this.currentPage - 1) * this.pageSize;
			const end = start + this.pageSize;

			// 模拟异步加载
			setTimeout(() => {
				const newData = this.allEmployeeList.slice(start, end);
				if (this.currentPage === 1) {
					this.displayEmployeeList = newData;
				} else {
					this.displayEmployeeList = [...this.displayEmployeeList, ...newData];
				}

				this.hasMore = end < this.allEmployeeList.length;
				this.isLoading = false;
				this.isRefreshing = false;
			}, 500);
		},

		// 下拉刷新
		async onRefresh() {
			this.isRefreshing = true;
			this.currentPage = 1;
			await this.loadPageData();
		},

		// 下拉过程
		onPulling(e) {
			console.log('pulling', e);
		},

		// 优化加载更多方法
		onLoadMore() {
			if (this.hasMore && !this.isLoading) {
				this.isLoading = true;
				this.currentPage++;
				// 模拟网络请求延迟
				setTimeout(() => {
					this.loadPageData();
				}, 500);
			}
		},

		// 重置数据
		resetData() {
			this.currentPage = 1;
			this.displayEmployeeList = [];
			this.hasMore = true;
			this.isLoading = false;
			this.isRefreshing = false;
		},
	},
	mounted() {
		this.generateCalendar();
		this.listenOrientationChange();

		// 根据当前方向设置初始状态
		if (window.orientation === 90 || window.orientation === -90) {
			this.isLandscape = true;
		}

		// 初始化图表
		this.$nextTick(() => {
			this.initChart();
		});
		this.initData();
	}
}
</script>

<style lang="scss" scoped>
.attendance-manage-container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: #f5f5f5;
	position: relative;
}

/* 图表样式 */
.chart-container {
	margin: 20rpx 30rpx;
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	border: 1px solid #eee;
	height: 480rpx;
	position: relative;
}

.chart-header {
	display: flex;
	justify-content: center;
	gap: 40rpx;
	margin-bottom: 20rpx;
}

.legend-item {
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.legend-dot {
	width: 20rpx;
	height: 20rpx;
	border-radius: 50%;
}

.factory-dot {
	background-color: #00C7F2;
}

.company-dot {
	background-color: #0FCA7A;
}

.chart-title {
	text-align: center;
	color: #666;
	font-size: 28rpx;
	margin-top: 10rpx;
}

.echarts-box {
	height: 360rpx;
	width: 100%;
}

.echarts-container {
	height: 100%;
	width: 100%;
}

.showFullScreenImage {
	overflow: hidden;
	height: calc(100vh - 200rpx);
}

/* 横屏模式样式 */
.landscape-mode {
	flex-direction: column;
	padding: 0;
	width: 100vw;
	min-height: 100vh;
	background-color: #fff;

	.main-content {
		padding-bottom: 0;
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.employee-table {
		margin: 0;
		border-radius: 0;
		height: 100%;
		width: 100vw;
		border: none;
	}

	.table-container {
		height: 100%;
		width: 100vw;
	}

	.table-header {
		background-color: #f8f8f8;
	}

	.header-cell,
	.cell {
		flex: 0 0 150rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.date-day-container {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.date-text {
		font-size: 24rpx;
		color: #666;
	}

	.day-text {
		font-size: 24rpx;
		color: #333;
		font-weight: 500;
	}

	.table-body {
		height: calc(100% - 110rpx);
	}

	.table-row:nth-child(odd) {
		background-color: #f5f5f5;
	}
}

/* 横竖屏切换按钮 */
.orientation-toggle {
	position: fixed;
	right: 20rpx;
	bottom: 20rpx;
	background-color: rgba(23, 163, 100, 0.8);
	color: white;
	padding: 10rpx 20rpx;
	border-radius: 50rpx;
	z-index: 100;
}

/* 顶部标题样式 */
.header {
	padding: 40rpx 0;
	background-color: #fff;
	display: flex;
	justify-content: space-between;
	border-bottom: 1px solid #eee;
	align-items: center;
}

.terminal-selector {
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
}

.terminal-title {
	font-size: 38rpx;
	font-weight: 500;
	color: #333;
	margin-right: 10rpx;
}

/* 周选择器样式 */
.week-selector {
	margin: 30rpx;
	background-color: #fff;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	padding: 30rpx;
	border: 1px solid #eee;
}

.week-label {
	font-weight: 400;
	font-size: 12px;
	color: #475467;
	line-height: 15px;
	text-align: left;
	font-style: normal;
	text-transform: none;
	margin-right: 30rpx;
	font-weight: 400;
	display: flex;
	align-items: center;
	height: 50rpx;
	padding-right: 20rpx;
	margin-right: 20rpx;
	border-right: 1px solid #D0D5DD;
}

.line {
	font-size: 62rpx;
	color: #D0D5DD;
	font-weight: 300;
	line-height: 1;
	margin-left: 10rpx;
	display: inline-flex;
	align-items: center;
	transform: translateY(-4rpx);
}

.date-picker {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.calendar-icon {
	width: 38rpx;
	height: 38rpx;
	margin-right: 16rpx;
	color: #0E623D;
}

.selected-date {
	color: #333;
	flex: 1;
	font-weight: 400;
	font-size: 26rpx;
	color: #1D232E;
	line-height: 19px;
	text-align: left;
}

/* 导出按钮样式 */
.export-action {
	display: flex;
	justify-content: space-between;
	margin: 20rpx 30rpx 0 30rpx;
}

.export-icon {
	width: 50rpx;
	height: 50rpx;
}

/* 主内容区域 */
.main-content {
	margin: 30rpx 0 0 30rpx;
	flex: 1;
	overflow: visible;
	padding-bottom: 180rpx;
}

/* 员工表格样式 */
.employee-table {
	margin: 0;
	background-color: #fff;
	border-radius: 0;
	overflow: hidden;
	height: 100%;
	display: flex;
	flex-direction: column;
}

.table-container {
	flex: 1;
	overflow: hidden;
	display: flex;
	flex-direction: column;
}

.scroll-view-x {
	white-space: nowrap;
	width: 100%;
}

.table-header {
	display: flex;
	padding: 30rpx 0;
	border-bottom: 1px solid #eee;
	background-color: #fff;
	width: fit-content;
	min-width: 100%;
}

.header-cell {
	flex: 0 0 200rpx;
	padding: 0 20rpx;
	text-align: center;
	font-size: 24rpx;
	font-weight: 500;
	color: #333;
	display: flex;
	align-items: center;
	justify-content: center;
}

.date-day-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.date-text {

	margin-bottom: 8rpx;
}

.day-text {
	font-size: 24rpx;
	font-weight: 500;
}

.table-body {
	flex: 1;
	overflow-y: auto;
}

.table-row {
	display: flex;
	padding: 20rpx 0;
	border-bottom: 1px solid #f0f0f0;
	width: fit-content;
	min-width: 100%;
}

.cell {
	flex: 0 0 200rpx;
	padding: 0 20rpx;
	text-align: center;
	font-size: 24rpx;
	color: #333;
	display: flex;
	align-items: center;
	justify-content: center;
}


/* 底部固定导航 */
.footer {
	position: fixed;
	bottom: 130rpx;
	left: 0;
	right: 0;
	background-color: #fff;
	/* 兼容iPhone X及以上机型 */
	z-index: 10;
}

/* 底部导出按钮样式 */
.export-buttons {
	display: flex;
	padding: 0rpx 14rpx;
	justify-content: space-between;
	width: 100%;
}

.export-btn {
	height: 90rpx;
	border-radius: 100rpx;
	border: 2rpx solid #17A364;
	display: flex;
	align-items: center;
	justify-content: center;
}

.export-btn text {
	font-size: 34rpx;
	margin-left: 10rpx;
}

.download {
	width: 40rpx;
	height: 40rpx;
}

.employee-name {
	text-align: left;
	padding-left: 60rpx;
}

.fedex-id,
.employee-id {
	text-align: center;
}

/* 日期选择弹窗样式 */
.date-picker-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 30rpx;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 100;
	display: flex;
	justify-content: center;
	align-items: flex-end;
	/* 改为底部对齐 */
}

.date-picker-content {
	width: 100%;
	/* 宽度占满 */
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	/* 只保留顶部圆角 */
	padding: 30rpx;
	padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
	max-height: 90vh;
	overflow-y: auto;
	display: flex;
	flex-direction: column;
	animation: slideUp 0.3s ease;
	/* 添加向上滑动动画 */
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}

	to {
		transform: translateY(0);
	}
}

.calendar-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
}

.current-month {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.nav-arrow {
	width: 50rpx;
	height: 50rpx;
}

.week-days {
	display: flex;
	justify-content: space-between;
	padding: 20rpx 0;
	border-bottom: 1px solid #f0f0f0;
}

.week-day {
	flex: 1;
	text-align: center;
	font-size: 28rpx;
	color: #666;
}

.week-day.friday {
	color: #17A364;
	font-weight: bold;
}

.calendar-grid {
	display: flex;
	flex-wrap: wrap;
	padding: 20rpx 0;
}

.calendar-day {
	width: 14.2857%;
	height: 60rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	margin: 10rpx 0;
	position: relative;
}

.calendar-day text {
	font-size: 28rpx;
	color: #ccc;
	/* Changed to light gray for all dates */
	position: relative;
	z-index: 2;
}

.other-month text {
	color: #eee;
	/* Even lighter for other months */
}

.selectable {
	position: relative;
}

.non-selectable {
	opacity: 0.5;
}

.friday text {
	color: #17A364;
	font-weight: 500;
}

.other-month text {
	color: #eee !important;
	/* Force gray for dates from other months */
}

.selected,
.in-range {
	position: relative;
}

.selected::before,
.in-range::before {
	content: '';
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 60rpx;
	height: 60rpx;
	background-color: #17A364;
	border-radius: 50%;
	z-index: 1;
}

.selected text,
.in-range text {
	color: #fff !important;
}


.bottom-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	padding: 16rpx 30rpx;
	background: #fff;
	box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
	z-index: 100;

	.btn {
		flex: 1;
		height: 80rpx;
		border-radius: 40rpx;
		font-size: 32rpx;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 10rpx;
		border: none;
	}

	.reject-btn {
		background: #ff5252;
	}

	.agree-btn {
		background: #19b36e;
	}
}


/* 公司选择弹窗样式 */
.company-selector-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 100rpx;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 100;
	display: flex;
	justify-content: center;
	align-items: flex-end;
	/* 改为底部对齐 */
}

.company-selector-content {
	width: 100%;
	/* 宽度占满 */
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	/* 只保留顶部圆角 */
	padding: 30rpx;
	display: flex;
	flex-direction: column;
	animation: slideUp 0.3s ease;
	/* 添加向上滑动动画 */
}

.company-selector-title {
	font-size: 38rpx;
	color: #333;
	font-weight: 500;
	text-align: center;
	margin-bottom: 40rpx;
}

.company-list {
	margin-bottom: 40rpx;
}

.company-item {
	display: flex;
	align-items: center;
	padding: 30rpx 0;
	border-bottom: 1px solid #f0f0f0;
}

.radio-circle {
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	border: 2rpx solid #E5E7EB;
	margin-right: 20rpx;
	background-color: #F9F9F9;
}

.radio-selected {
	border: 8rpx solid #17A364;
	background-color: #fff;
}

.company-item text {
	font-size: 34rpx;
	color: #333;
}

.close-company-btn {
	margin-top: 20rpx;
	height: 90rpx;
	border-radius: 100rpx;
	border: 1px solid #17A364;
	display: flex;
	justify-content: center;
	align-items: center;
}

.close-company-btn text {
	color: #17A364;
	font-size: 34rpx;
}

/* 横屏模式下的滚动条样式 */
.landscape-scroll {
	scroll-behavior: smooth;
	/* 使滚动更平滑 */
}

/* Update the styles for the full-screen image viewer at the end of the style section */
.fullscreen-image-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: #FFFFFF;
	z-index: 1000;
	display: flex;
	justify-content: center;
	align-items: center;
}

.zoom-container {
	width: 100vw;
	height: 100vh;
	display: flex;
	justify-content: center;
	align-items: center;
	overflow: hidden;
}

.fullscreen-image {
	width: 100vw;
	height: 100vh;
	object-fit: cover;
	will-change: transform;
	transform-origin: center;
}

.close-fullscreen-btn {
	position: absolute;
	top: 40rpx;
	right: 40rpx;
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background-color: rgba(0, 0, 0, 0.3);
	display: flex;
	justify-content: center;
	align-items: center;
}

.close-fullscreen-btn text {
	color: #fff;
	font-size: 60rpx;
	font-weight: 300;
}

/* Add styling for the field cells */
.field-cell {
	flex: 0 0 180rpx;
	min-width: 180rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

/* 加载更多样式优化 */
.load-more-container {
	padding: 30rpx 0;
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
}

.loading-more {
	display: flex;
	align-items: center;
	justify-content: center;
	color: #666;
	font-size: 28rpx;
}

.loading-spinner {
	width: 40rpx;
	height: 40rpx;
	border: 4rpx solid #f3f3f3;
	border-top: 4rpx solid #17A364;
	border-radius: 50%;
	margin-right: 20rpx;
	animation: spin 1s linear infinite;
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

.load-more-btn {
	background-color: #17A364;
	color: #fff;
	padding: 20rpx 60rpx;
	border-radius: 50rpx;
	font-size: 28rpx;
	cursor: pointer;
}

.load-more-btn:active {
	opacity: 0.8;
}

.no-more {
	color: #999;
	font-size: 28rpx;
	text-align: center;
}

.edit-cell {
	flex: 0 0 80rpx !important;
	min-width: 80rpx !important;
	padding: 0 10rpx !important;
	display: flex;
	align-items: center;
	justify-content: center;
}

.edit-icon {
	width: 40rpx !important;
	height: 40rpx !important;
	padding: 0 !important;
}

.edit-icon:active {
	opacity: 0.7;
}
</style>